package com.imist.sm.global;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String path = request.getServletPath();
        if (path.toLowerCase().indexOf("login") != -1){
            //登陆相关的请求先放过
            filterChain.doFilter(request,response);
        }else {
            HttpSession session = request.getSession();
            Object obj = session.getAttribute("USER");
            if (obj != null){
                //已经登陆的请求放过
                filterChain.doFilter(request,response);
            }else {
                //没有登录就回到登录界面,注意过滤到的请求路径很复杂，可能多级目录，所以不能用相对路径;
                response.sendRedirect(request.getContextPath()+"/toLogin.do");
            }
        }
    }
}
